﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition.Hosting;
using Cinch;
using MEFedMVVM.ViewModelLocator;
using CodeStash.Addin.Core;
using CodeStash.Addin.ViewModels;

namespace CodeStash.Addin.MEF
{
    public class MEFPartsResolver
    {

        private CompositionContainer container;
        private static readonly Lazy<MEFPartsResolver> instance = new Lazy<MEFPartsResolver>(() => new MEFPartsResolver());
        private AddinExportProvider provider;

        private MEFPartsResolver()
        {

        }

        public static MEFPartsResolver Instance
        {
            get
            {
                return instance.Value;
            }
        }


        public T Resolve<T>()
        {
            return container.GetExport<T>().Value;
        }



        public object GetExportForView(object view, string contractName)
        {
            provider.SetContextToInject(view);
            Type t = view.GetType();
            var vm = container.GetExport<object>(contractName);
            //provider.SetContextToInject(null);
            return vm.Value;

        }



        public void Configure()
        {

            AggregateCatalog aggCat = new AggregateCatalog();
            aggCat.Catalogs.Add(new AssemblyCatalog(typeof(ViewModelBase).Assembly));
            aggCat.Catalogs.Add(new AssemblyCatalog(typeof(ExportViewModel).Assembly));
            aggCat.Catalogs.Add(new AssemblyCatalog(typeof(AddSnippetViewModel).Assembly));
            aggCat.Catalogs.Add(new AssemblyCatalog(typeof(LanguageService).Assembly));
            //aggCat.Catalogs.Add(new AssemblyCatalog(typeof(DocumentService).Assembly));

            

            provider = new AddinExportProvider(aggCat);
            container = new CompositionContainer(provider);
            provider.SourceProvider = container;
        }
    }

}
